package cn.com.easy.permission.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.easy.permission.dao.ResourceDao;
import cn.com.easy.permission.dao.RoleDao;
import cn.com.easy.permission.dao.RoleResourceMappingDao;
import cn.com.easy.permission.dao.UserDao;
import cn.com.easy.permission.dao.UserRolesMappingDao;
import cn.com.easy.permission.model.ResourceModel;
import cn.com.easy.permission.model.RoleModel;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.model.UserRolesMappingModel;
import cn.com.easy.permission.service.system.role.SystemRoleService;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.permission.web.dto.system.ResourceDto;
import cn.com.easy.utils.FastJSONUtils;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;

/**
 * 角色管理
 * 
 * @author nibili 2015年12月8日
 * 
 */
@Controller
@RequestMapping("/manage/system/role")
public class SystemRoleController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SystemRoleController.class);

	/** 角色dao */
	@Autowired
	private RoleDao roleDao;
	/** 角色资源对应表 */
	@Autowired
	private RoleResourceMappingDao roleResourceMappingDao;
	/** 功能菜单 资源表dao */
	@Autowired
	private ResourceDao resourceDao;
	/** 角色服务类 */
	@Autowired
	private SystemRoleService systemRoleService;
	/** 成员表dao */
	@Autowired
	private UserDao userDao;
	/** 用户角色映射表dao */
	@Autowired
	private UserRolesMappingDao userRolesMappingDao;

	/**
	 * 首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("首页")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/system/system_role/system_role";
	}

	/**
	 * 获取所有角色
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取所有角色")
	@RequestMapping("/get/all")
	public void getAllRoles(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {
			Page<RoleModel> springDataPage = roleDao.findAll(pageRequestParamDTO.buildSpringDataPageRequest());
			cn.com.easy.utils.Page<RoleModel> page = PageUtils.getPage(springDataPage);
			// page.setTotalItems(1000);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 保存或更新角色
	 * 
	 * @param request
	 * @param response
	 * @param roleModel
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("保存或更新角色")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveOrUpdateRole(HttpServletRequest request, HttpServletResponse response, RoleModel roleModel) {
		try {
			if (roleModel.getId() == null) {
				// 新增
				roleDao.save(roleModel);
			} else {
				// 更新
				RoleModel roleModelTemp = roleDao.findOne(roleModel.getId());
				if (roleModelTemp == null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交角色信息失败，未找到用户！"));
					return;
				} else {
					roleModelTemp.setIsEnable(roleModel.getIsEnable());
					roleModelTemp.setName(roleModel.getName());
					roleModelTemp.setMark(roleModel.getMark());
					roleDao.save(roleModelTemp);
				}
			}
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("提交角色信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交角色信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("删除角色")
	@RequestMapping(value = "/delete")
	public void deleteRole(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			// 删除角色
			systemRoleService.deleteRoleById(id);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("删除角色异常，id:" + id, ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取指定角色的权限资源树
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("获取指定角色的权限资源树")
	@RequestMapping("/get/resources")
	public void getMemberInRole(HttpServletRequest request, HttpServletResponse response, Long roleId) {
		try {

			// 一、找出指定角色的权限id列表
			List<Long> resourceIdList = roleResourceMappingDao.findResourceIdByParentId(roleId);
			// 二、找出系统所有资源
			List<ResourceModel> result = resourceDao.findAll();
			List<ResourceDto> resourcelList = FastJSONUtils.toArray(FastJSONUtils.toJsonString(result), ResourceDto.class);
			// 三、把选中的权限资源节点打上标记
			if (CollectionUtils.isNotEmpty(resourcelList) == true && CollectionUtils.isNotEmpty(resourceIdList) == true) {
				for (ResourceDto resourceDto : resourcelList) {
					if (resourceIdList.contains(resourceDto.getId())) {
						// 角色有该节点的权限
						resourceDto.setChecked(true);
					}
				}
			}
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, resourcelList));
		} catch (Exception ex) {
			logger.error("获取所有角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	// /**
	// * 读取资源树
	// *
	// * @param parentId
	// * @return
	// * @author nibili 2015年12月10日
	// */
	// private List<ResourceDto> readResourceModel(Long parentId) {
	// List<ResourceModel> result = resourceDao.findByParentId(parentId);
	// List<ResourceDto> list =
	// FastJSONUtils.toArray(FastJSONUtils.toJsonString(result),
	// ResourceDto.class);
	// if (CollectionUtils.isNotEmpty(list) == true) {
	// // 查找字典
	// List<ResourceDto> listTemp = this.readResourceModel(parentId);
	// if (CollectionUtils.isNotEmpty(listTemp) == true) {
	// list.addAll(listTemp);
	// }
	// }
	// return list;
	// }

	/**
	 * 保存或更新角色权限
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 *            角色id
	 * @param resourceIds
	 *            资源id
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("保存或更新角色权限")
	@RequestMapping(value = "/save/resources", method = RequestMethod.POST)
	public void saveRoleResources(HttpServletRequest request, HttpServletResponse response, Long roleId, String resourceIdsString) {
		try {
			if (StringUtils.isBlank(resourceIdsString) == true || roleId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色id 或者 功能菜单id 为空！"));
				return;
			}
			RoleModel roleModelTemp = roleDao.findOne(roleId);
			if (roleModelTemp == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色信息查找失败，未找到该角色！"));
				return;
			} else {
				// 更新角色权限
				systemRoleService.saveRoleResources(roleId, resourceIdsString);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("提交角色权限信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交角色权限信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取角色中的成员
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @param roleId
	 *            角色id
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("获取角色中的成员")
	@RequestMapping("/get/members")
	public void getMemberInRole(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO, Long roleId) {
		try {
			// 默认按添加时间降序排序
			pageRequestParamDTO.setSortName("createTime");
			pageRequestParamDTO.setSortOrder("desc");
			Page<UserModel> springDataPage = null;
			if (StringUtils.isNotBlank(pageRequestParamDTO.getSearchText()) == true) {
				// 搜索字段不为空
				springDataPage = userRolesMappingDao
						.findUserModelByRoleIdAndNameLike(roleId, pageRequestParamDTO.getSearchText(), pageRequestParamDTO.buildSpringDataPageRequest());
			} else {
				springDataPage = userRolesMappingDao.findUserModelByRoleId(roleId, pageRequestParamDTO.buildSpringDataPageRequest());
			}
			cn.com.easy.utils.Page<UserModel> page = PageUtils.getPage(springDataPage);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有角色异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有角色异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取系统所有成员
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取系统所有成员")
	@RequestMapping("/get/members/all")
	public void getAllMembers(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {
			Page<UserModel> springDataPage = null;
			if (StringUtils.isNotBlank(pageRequestParamDTO.getSearchText()) == true) {
				// 搜索字段不为空
				springDataPage = userDao.findLikeLoginnameOrRealname(pageRequestParamDTO.getSearchText(), pageRequestParamDTO.buildSpringDataPageRequest());
			} else {
				springDataPage = userDao.findAll(pageRequestParamDTO.buildSpringDataPageRequest());
			}
			cn.com.easy.utils.Page<UserModel> page = PageUtils.getPage(springDataPage);
			// page.setTotalItems(1000);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 添加角色成员
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 * @param memberId
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("添加角色成员")
	@RequestMapping(value = "/add/member")
	public void addMember(HttpServletRequest request, HttpServletResponse response, Long roleId, Long memberId) {
		try {
			if (memberId == null || roleId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色id 或者 成员id 为空！"));
				return;
			}
			RoleModel roleModelTemp = roleDao.findOne(roleId);
			if (roleModelTemp == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色信息查找失败，未找到该角色！"));
				return;
			} else {
				UserRolesMappingModel userRolesMappingModel = userRolesMappingDao.findByRoleIdAndUserId(roleId, memberId);
				if (userRolesMappingModel != null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "成员已存在！"));
					return;
				}
				// 添加角色成员
				userRolesMappingModel = new UserRolesMappingModel();
				userRolesMappingModel.setCreateBy(this.getCurrentUser(request).getLoginname());
				userRolesMappingModel.setUserId(memberId);
				userRolesMappingModel.setRoleId(roleId);
				userRolesMappingDao.save(userRolesMappingModel);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("添加角色成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "添加角色成员异常.ex:" + ex.getLocalizedMessage()));
		}

	}

	/**
	 * 删除角色成员
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 * @param memberId
	 * @author nibili 2015年12月10日
	 */
	@UrlReserveAnotion("删除角色成员")
	@RequestMapping(value = "/delete/member")
	public void deleteMember(HttpServletRequest request, HttpServletResponse response, Long roleId, Long memberId) {
		try {
			if (memberId == null || roleId == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色id 或者 成员id 为空！"));
				return;
			}
			RoleModel roleModelTemp = roleDao.findOne(roleId);
			if (roleModelTemp == null) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色信息查找失败，未找到该角色！"));
				return;
			} else {
				// 角色成员
				systemRoleService.deleteMember(roleId, memberId);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("删除角色成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "角色成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
